//
//  mttViewController.m
//  mtt
//
//  Created by Gerfried Mikusch on 16.04.2010.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "mttViewController.h"
#import "OptionViewController.h"
#import "mttImage.h"
#import "mttBackgroundImage.h"
#import "mttPoint.h"
#import "mttImageGroup.h"

@implementation mttViewController

@synthesize images, imageGroups, help;

NSMutableDictionary *pins;
NSMutableDictionary *pinnedImages;
NSNumber *imagekey;
NSNumber *imageGroupKey;
int pinID = 0;
mttBackgroundImage *bgImage;
OptionViewController *optionView;
BOOL isKreis;
NSMutableArray *neueGroupImages;


#pragma mark -
#pragma mark test methods

-(void)printOutGeometryOfImagesOnAction:(NSString *) action {
	
	NSLog(@"START IMAGE GEOMETRY AT: %s --------------------------------------", action);
	
	
	for (int i=0; i<images.count; i++) {
		
		mttImage *actualImage = [images objectForKey:[NSNumber numberWithInt:i]];
		
		NSLog(@"START IMAGE NR: %i +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", actualImage.imagekey);
		NSLog(@"IMAGE VIEW FRAME: x:%f, y:%f, w:%f, h:%f", actualImage.frame.origin.x, actualImage.frame.origin.y, actualImage.frame.size.width, actualImage.frame.size.height);
		//NSLog(@"IMAGE VIEW BOUNDS: x:%f, y:%f, w:%f, h:%f", actualImage.bounds.origin.x, actualImage.bounds.origin.y, action.bounds.size.width, actualImage.bounds.size.height);
		NSLog(@"IMAGE VIEW CENTER: x:%f, y:%f", actualImage.center.x, actualImage.center.y);
		NSLog(@"IMAGE LAYER FRAME: x:%f, y:%f, w:%f, h:%f", actualImage.layer.frame.origin.x, actualImage.layer.frame.origin.y, actualImage.layer.frame.size.width, actualImage.layer.frame.size.height);
		//NSLog(@"IMAGE LAYER BOUNDS: x:%f, y:%f, w:%f, h:%f", actualImage.layer.bounds.origin.x, actualImage.layer.bounds.origin.y, action.layer.bounds.size.width, actualImage.layer.bounds.size.height);
		NSLog(@"IMAGE LAYER POSITION: x:%f, y:%f", actualImage.layer.position.x, actualImage.layer.position.y);
		NSLog(@"IMAGE LAYER ANCHOR: x:%f, y:%f", actualImage.layer.anchorPoint.x, actualImage.layer.anchorPoint.y);
		NSLog(@"END IMAGE NR: %i +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", actualImage.imagekey);
		
	}
	
	
	NSLog(@"END IMAGE GEOMETRY AT: %s --------------------------------------", action);
	
}



#pragma mark -
#pragma mark loading/unload the View

- (void)viewDidLoad {
    [super viewDidLoad];
	
	
	//Load Option View
	optionView = [[OptionViewController alloc] initWithNibName:@"OptionViewController" bundle:[NSBundle mainBundle]];
	optionView.delegate = self;
	//optionView = optionViewCont.view;
	
	
	//Size & Position of OptionView
	CGFloat optionViewFrameWidth = optionView.view.frame.size.width;						//Width = 80
	CGFloat superViewFrameWidth = self.view.frame.size.width;								//Width = 768 -> sollte eigentlich 1024 sein da Querformat
	CGFloat newXOrigin = superViewFrameWidth - optionViewFrameWidth;
	
	CGFloat optionViewFrameHeight = optionView.view.frame.size.height;						//Height = 130
	CGFloat superViewFrameHeight = self.view.frame.size.height;								//Height = 1024 -> sollte eigentlich 768 sein da Querformat
	CGFloat newYOrigin = superViewFrameHeight - optionViewFrameHeight;
	
	CGRect rect = optionView.view.frame;
	rect.origin = CGPointMake(newXOrigin+optionViewFrameWidth, newYOrigin);					//X = 690; Y = 899
	//rect.size = CGSizeMake(optionView.view.frame.size.width, optionView.view.frame.size.height);		
	optionView.view.frame = rect;
	
	
	//Hier Animationsanfang!?
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:context];
	
	[UIView setAnimationDuration:1.0];
	
	optionView.view.transform = CGAffineTransformMakeTranslation(-optionViewFrameWidth, 0);			//Warum 300????
	
	
	[self.view addSubview:optionView.view];		//Add LibraryView as Subview
	[UIView commitAnimations];
	//Hier Animationsende!?
	
	
	//dict für die hinzugefuegten images, imageGroups, und pinned images
	images = [[NSMutableDictionary alloc] init];
	imageGroups = [[NSMutableDictionary alloc] init];
	pinnedImages = [[NSMutableDictionary alloc] init];
	imagekey = [NSNumber numberWithInt:0];
	imageGroupKey = [NSNumber numberWithInt:0];
	pins = [[NSMutableDictionary alloc]init];
	neueGroupImages = [[NSMutableArray alloc] init];
	/*
	//!!!: TEST für die gezeichneten Pins - danach wieder löschen
	mttPoint *pin = [[mttPoint alloc] initWithFrame:CGRectMake(100, 100, 25, 25)];
	[self.view addSubview:pin];
	*/
	
	
}

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark -
#pragma mark Setting Views (Images, imageGroup)

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	
	//mttImage erstellen und mit dem Bild aus imagePicker initialisieren
	mttImage *mttImg = [[mttImage alloc] initWithImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
	
	mttImg.delegate = self;
	
	//Bilder im Zentrum einfügen
	mttImg.layer.position = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
	
	//Sind die Bilder größer als das Display, sollen sie verkleinert werden
	if (mttImg.frame.size.width > self.view.frame.size.width || mttImg.frame.size.height > self.view.frame.size.height) {
		mttImg.contentMode = UIViewContentModeScaleAspectFill;
		
		CGRect rect = self.view.frame;
		rect.size = CGSizeMake(1024, 768);
		mttImg.frame = rect;
	}
	
	
	[self.view addSubview:mttImg];
	//[self.view bringSubviewToFront:optionView.view];
	[self bringOptionViewToFront];
	
	[images setObject:mttImg forKey:imagekey];
	mttImg.imagekey = imagekey;
		
	//Bild zur verknüpfungsliste hinzufügen mit leerem mutable Array
	NSMutableArray *pinnedToActualImage = [[NSMutableArray alloc] init];
	[pinnedImages setObject:pinnedToActualImage forKey:imagekey];
	
	int newKey = [imagekey intValue] +1;
	imagekey = [NSNumber numberWithInt:newKey];
	
	
	/*NSLog(@"imagekey:");
	for (id key in images) {
		
        NSLog(@"key: %@, value: %@", key, [images objectForKey:key]);
		
    }
	*/
	
	//Wenn gerade ein Hintergrundbild bearbeitet wird -> bearbeiten ausschalten!
	if (bgImage != nil && bgImage.panRecognizer.enabled == YES) {
		[bgImage setGestureRecognizersEnabled:NO];				//GestureRecognizer beim Hintergrund disablen
		[self setImagesAlpha:1.0];								//Keine Transparenz der Bilder
		[self setImagesInteraction:YES];						//Interaction der Bilder einschalten
	}
	
	[pinnedToActualImage release];    //!!!: Achtung. Ist dieses release hier richtig?????
}

- (CGRect)getGroupRectForImages:(NSMutableArray *) imgs {
	
	
	mttImage *firstImg = [images objectForKey:[imgs objectAtIndex:0]];
	
	
	CGRect firstRect = [firstImg convertRect:firstImg.bounds toView:self.view];
	
	CGFloat maxX = firstRect.origin.x;
	CGFloat minX = firstRect.origin.x + firstRect.size.width;
	CGFloat maxY = firstRect.origin.y;
	CGFloat minY = firstRect.origin.y + firstRect.size.height;
	
	
	//Neue Position und Größe der GroupeView ermitteln
	for (int i=0; i<imgs.count; i++) {
		
		mttImage *actualImage = [images objectForKey:[imgs objectAtIndex:i]];
		
		CGRect actualRect = [actualImage convertRect:actualImage.bounds toView:self.view];
		
		//Check minX
		if (actualRect.origin.x < minX ) minX = actualRect.origin.x;
		
		//Check maxX
		if ((actualRect.origin.x + actualRect.size.width) > maxX) maxX = actualRect.origin.x + actualRect.size.width;
		
		//Check minY
		if (actualRect.origin.y < minY ) minY = actualRect.origin.y;
		
		//Check maxY
		if ((actualRect.origin.y + actualRect.size.height) > maxY) maxY = actualRect.origin.y + actualRect.size.height;
		
	}
	
	return CGRectMake(minX, minY, maxX-minX, maxY-minY);
	
}

-(void)dismissUnusedGroupViews {
	
	NSMutableArray *groupsToDelete = [[NSMutableArray alloc] init];
	
	for (id key in imageGroups) {
		
		mttImageGroup *actualGroup = [imageGroups objectForKey:key];
		
		//Wenn die Gruppe keine Subviews (also bilder hat) ist sie zu löschen
		if (actualGroup.subviews.count == 0) {
			[groupsToDelete addObject:actualGroup];
		}
	}
	
	
	//Groups endgültig löschen
	for (int i=0; i<groupsToDelete.count; i++) {
		mttImageGroup *actualGroup = [groupsToDelete objectAtIndex:i];
		[actualGroup removeFromSuperview];
		[imageGroups removeObjectForKey:actualGroup.imageGroupKey];
		[actualGroup release];
	}
	
	[groupsToDelete release];
	
	// Eintrag aus dictionary wird offenbar nicht gelöscht!
	/*for (id key in imageGroups) {
		NSLog(@"---------------------    imageGroups nach löschen---------------------------");
        NSLog(@"key: %@, value: %@", key, [imageGroups objectForKey:key]);
		
    }*/
	
}

#pragma mark -
#pragma mark image searching



-(NSMutableArray *)getImagesAtPoint:(CGPoint)point {
	
	
	
	NSMutableArray *imagesAtPoint = [[NSMutableArray alloc] init];
	
	//Durchlaufe alle Bilder und überprüfe ob sie an diesem Punkt liegen
	for (int i=0; i<=images.count; i++) {
		mttImage *img = (mttImage *)[images objectForKey:[NSNumber numberWithInt:i]];
		
		CGPoint pointForView = [img convertPoint:point fromView:nil];
		//NSLog(@"pointForView: %i x: %f, y: %f", img.imagekey, pointForView.x, pointForView.y);
		
		//Liegt ein bild an dem Punkt füge die id des bilds als NSNumber hinzu
		if ([img hitTest:pointForView withEvent:nil] != nil) {
			[imagesAtPoint addObject:img.imagekey];
		}
		
	}
	
	return imagesAtPoint;
	
}

-(BOOL)isImageAttached:(NSNumber *)attachedID atImage:(NSNumber *)imageID {
	
	//Hängt das bild mit attachedID schon beim bild mit ImageID dabei?
		
		BOOL isAttached = NO;
		
	//das passt nicht, weil hier nur die angehängten bilder genommen werden, aber nicht das bild bei dems dabeihängt selbst ??
		NSMutableArray *imagesAtImage = [pinnedImages objectForKey:imageID];
		
		for (int i=0; i<imagesAtImage.count; i++) {
			if([[imagesAtImage objectAtIndex:i] isEqualToNumber:attachedID]) isAttached = YES;
			//NSLog(@"bla");
		
		}
		//if ([attachedID intValue] == [imageID intValue]) {
	if( [attachedID isEqualToNumber:imageID]) {
			isAttached = YES;}
		 
		return isAttached;
	

}

-(BOOL)isID:(NSNumber *)myID inArray:(NSMutableArray *)array {
	
	BOOL retVal = NO;
	
	for (int i=0; i<array.count; i++) {
		if ([[array objectAtIndex:i] isEqualToNumber:myID]) {
			retVal = YES;
		}
	}
	
	return retVal;
	
}

-(void)addNextImage:(NSMutableArray *)next toActualImage:(NSMutableArray *)actual {
	
	for (int i=0; i<next.count; i++) {
		for (int j=0; j<actual.count; j++) {
			
			if (![self isImageAttached:[next objectAtIndex:i] atImage:[actual objectAtIndex:j]]) {
				//[actual addObject:[next objectAtIndex:i]];
				[[pinnedImages objectForKey:[actual objectAtIndex:j]] addObject:[next objectAtIndex:i]];
			}
			
		}
	}
	
}




#pragma mark -
#pragma mark Image & Image Group Delegate Methods


-(BOOL)isPinPossible:(NSNumber *)callerID atPoint:(CGPoint) hitPoint {
	
	mttImage *callImg = [images objectForKey:callerID];
	
	for (int i=0; i<images.count; i++) {
	
		mttImage *actualImage = [images objectForKey:[NSNumber numberWithInt:i]];
		
		CGPoint convPoint = [callImg convertPoint:hitPoint toView:actualImage];
		
		if ([actualImage hitTest:convPoint withEvent:nil] != nil && actualImage.imagekey != callImg.imagekey) {
			return YES;
		}
	}
	
	return NO;
	
}


-(void)performPinOnImages:(CGPoint)pinPoint withCallerId:(NSNumber*)callerId {
	
	/* !!!: Location des pinPoint ist in device-Koordinaten*/

		
	//Bilder die diesen PinPoint erhalten sollen
	NSMutableArray *imagesToPin = [self getImagesAtPoint:pinPoint];
	
	//!!!: Bug#2 - Diesen teil an der richtigen stelle wieder einfügen!!!!
	//Ein dictionary erstellen, in dem die direkten images, die zu pinnen (waren) gepeichert werden ... is fuers loeschen ...
	NSLog(@"imagestopin vorher %@",imagesToPin);
	
	
	
	
	
	
	//NSLog(@"imagesToPin ....... %i", imagesToPin.count);
	//Nur wenn überhaupt ein bild darunter liegt soll  allen Bildern ein pinPoint zugewiesen werden
	if (imagesToPin.count>1) {
		
		
		for (int i = 0; i<imagesToPin.count-1; i++) {
			
			mttImage *actualImage = (mttImage *)[images objectForKey:[imagesToPin objectAtIndex:i]];
			mttImage *nextImage = (mttImage *)[images objectForKey:[imagesToPin objectAtIndex:i+1]];
			
			NSMutableArray *attachedToActual = [pinnedImages objectForKey:actualImage.imagekey];
			NSMutableArray *attachedToNext = [pinnedImages objectForKey:nextImage.imagekey];
			
			if (i == 0 && ![self isID:actualImage.imagekey inArray:attachedToActual]) {
				//if (attachedToActual.count <= 1){
				[attachedToActual addObject:actualImage.imagekey];
				//}
			}
			//[attachedToActual addObject:actualImage.imagekey];
			if (![self isID:nextImage.imagekey inArray:attachedToNext]) {
				[attachedToNext addObject:nextImage.imagekey];
			}
			
			[self addNextImage:attachedToNext toActualImage:attachedToActual];
			[self addNextImage:attachedToActual toActualImage:attachedToNext];
			
		}
		
	
		
		for (int i=0; i<imagesToPin.count; i++) {
			mttImage *actualImage = (mttImage *)[images objectForKey:[imagesToPin objectAtIndex:i]];
			
			
			//!!!:	Bug#2 Lösung: Jede View darf nur eine Superview haben, darum sollte für jedes Bild ein neues Pin-Objekt erstellt werden.
			//		Allerdings Achtung - was bedeuted das fürs Löschen der Pins. Wir haben jetzt eine eigene ID für jeden Pin auf jedem Bild! Werden drei Bilder gepinnt, haben wir auch drei pins!!!
			mttPoint *pin = [[mttPoint alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
			
			pin.pinID = pinID;
			NSLog(@"PIN ID BEIM PINNEN: %i", pin.pinID);
				
			pin.delegate = self;
			
			[actualImage setPin:pin atPoint:pinPoint];
			[actualImage logPinPoints:actualImage.imagekey];
			
		}
		NSNumber *pinIDnumber = [[NSNumber alloc] initWithInt:pinID];
		[pins setObject:imagesToPin forKey:pinIDnumber];
		[pinIDnumber release];
		pinID = pinID + 1;
		
	
	
		/*	ImageGroup erzeugen
					Alle zusammenhängenden Bilder sollen in eine mttImageGroup die als Subview dem mainController hinzugefügt werden.
					Die Bilder werden wiederum der ImageGroup als Subview hinzugefügt.
		*/
	
		
		
		
		//NSLog(@"GroupRect x:%f, y:%f, w:%f, h:%f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
		
		
		
		NSMutableArray* keysForGroup = [pinnedImages objectForKey:callerId];
		
		// Init mit mainController frame
		//mttImageGroup* imageGroup = [[mttImageGroup alloc] initWithFrame:self.view.bounds];		

		// Init mit berechnetem Frame. ResizetoSubviews unten weiter ist überflüssig
		mttImageGroup* imageGroup = [[mttImageGroup alloc] initWithFrame:[self getGroupRectForImages:keysForGroup]];	
		
		imageGroup.delegate = self;
		imageGroup.imageGroupKey = imageGroupKey;
		//imageGroup.backgroundColor = [UIColor colorWithRed:2 green:2 blue:2 alpha:2];
		
		for(int i = keysForGroup.count-1; i>=0; i--){
	
			mttImage* actualImage = [images objectForKey:[keysForGroup objectAtIndex:i]];
			//NSLog(@"New Pin -----------------------");
			
			[imageGroup addSubview:actualImage];
			//NSLog(@"ImageFrame after x:%f, y:%f, w:%f, h:%f", actualImage.frame.origin.x, actualImage.frame.origin.y, actualImage.frame.size.width, actualImage.frame.size.height);
			//NSLog(@"imagePosition after x:%f, y:%f", actualImage.layer.position.x, actualImage.layer.position.y);
			//NSLog(@"GroupPosition x:%f, y:%f", imageGroup.layer.position.x, imageGroup.layer.position.y);
			
			//Gesture Recognizer für das Bild abschalten
			[actualImage setGestureRecognizersEnabled:NO];
			
			//Wenn die Pins angezeigt sind, sollen Sie ausgeschaltet werden
			[actualImage hideSubviews:YES];
			
		
		}
		
		[imageGroups setObject:imageGroup forKey:imageGroup.imageGroupKey];
	
		int newKey = [imageGroupKey intValue] + 1;
		imageGroupKey = [NSNumber numberWithInt:newKey];
	
		//[imageGroup resizeToSubviews];
	
		//NSLog(@"NEWS SIZE width: %f height: %f", size.width, size.height);
	
		[self.view addSubview:imageGroup];
		[self bringOptionViewToFront];
		
		
		//Leere ImageGroups verwerfen
		[self dismissUnusedGroupViews];
	
	}
	
	
	for (id key in pinnedImages) {
		NSLog(@"---------------------    Pinned Images ---------------------------");
        NSLog(@"key: %@, value: %@", key, [pinnedImages objectForKey:key]);
		
    }
	 
}



-(void)findeKreismitAnfangsImage:(mttImage *)testimage  schonbehandeltePins:(NSMutableArray *)abgehandeltePins  naechstesImage:(mttImage *)gesuchtesImage {
	//alle pins durchlaufen
	for(int i=0;i<pinID;i++){
		
		//todo: es sind eigentlich nur die pins interessant, die das gesuchte image enthalten....
		NSNumber *pinnumber = [[NSNumber alloc] initWithInt:i];
		NSLog(@"vor suchen");
		//suchen, ob die momentane pinnumber schon in den abgehandelten pins ist
		int istabgehandelt = 0;
		int gesuchtestimagegefunden=0;
		for(int g=0;g<[abgehandeltePins count];g++){
			if(pinnumber==[abgehandeltePins objectAtIndex:g]) { istabgehandelt++; }
		}
		
		NSLog(@"vor alle images der pins");
		//alle Images der pins (ausser der schon abgehandelten durchlaufen
		if(istabgehandelt==0){
			
		for(int f=0;f<[[pins objectForKey:pinnumber] count];f++){
			if([[pins objectForKey:pinnumber] objectAtIndex:f]==gesuchtesImage && gesuchtestimagegefunden==0){ gesuchtestimagegefunden++; f=0;}  
			
			NSLog(@"in findekreis in schleife");
			
			//NSLog(@"pins:
			//Wenn das image nach dem getestet wurde auf dem weg gefunden wird, ist ein kreis vorhanden
			if(gesuchtestimagegefunden>0){
				if([[pins objectForKey:pinnumber] objectAtIndex:f]==testimage  ){ NSLog(@"PIN IST IN KREIS !!!!!!"); 
																					isKreis = YES;
																				   [abgehandeltePins addObject:pinnumber]; 
																				   f=[[pins objectForKey:pinnumber] count];} else {
				[abgehandeltePins addObject:pinnumber];
				NSLog(@"neuer programmaufruf");
				if([abgehandeltePins count]<=pinID){
				[self findeKreismitAnfangsImage:testimage schonbehandeltePins:abgehandeltePins naechstesImage:[[pins objectForKey:pinnumber] objectAtIndex:f]];
				}
			}
			
			
			}	
		}
		}
		
	}
	
	
}

-(BOOL)findeKreis:(int)thisPinID {
	
	isKreis = NO;
	
	NSNumber *pintoremovenumber = [[NSNumber alloc] initWithInt:thisPinID];
	
	NSMutableArray *behandeltePins = [[NSMutableArray alloc] init];
	[behandeltePins addObject:pintoremovenumber];
	for(int i=1;i<[[pins objectForKey:pintoremovenumber] count];i++){
		NSLog(@"inremovePin in erster schleife"); 
		[self findeKreismitAnfangsImage:[[pins objectForKey:pintoremovenumber] objectAtIndex:0] schonbehandeltePins:behandeltePins naechstesImage:[[pins objectForKey:pintoremovenumber] objectAtIndex:i]];
	}
	
	return isKreis;
	
	
	
}




-(void)findeGruppe: (mttImage *) caller mitrotationpin:(mttPoint *) rotationpin {
	NSLog(@"IN FINDE GRUPPE caller.pinPoints=%i",[caller.pinPoints count]);
	//for(id key in caller.pinPoints){
	if([caller.pinPoints count]==0){ [neueGroupImages addObject:caller]; }
	for(id key in caller.pinPoints){
	NSLog(@"IN ERSTER FOR SCHLEIFE");
		
		int actualpinID = [[caller.pinPoints objectForKey:key] pinID];
		if(rotationpin!=[caller.pinPoints objectForKey:key]){
		//Array von images die auf dem pin draufhängen
		NSMutableArray* actualImages = [[NSMutableArray alloc] initWithArray:[pins objectForKey:[NSNumber numberWithInt:actualpinID]]];
		for(int f=0;f<[actualImages count];f++){
			//hier gehört noch gesucht ob das image vorhanden is, wenn nicht dann:
			int gefunden=0;
			for(int g=0;g<[neueGroupImages count];g++){
				if ([images objectForKey:[actualImages objectAtIndex:f]]==[neueGroupImages objectAtIndex:g]) {
					gefunden=1;	
					NSLog(@"GEFUNDEN!!");
				}
			}
			if(gefunden==0){
				NSLog(@"NICHT GEFUNDEN!!");
				[neueGroupImages addObject:[images objectForKey:[actualImages objectAtIndex:f]]];
				NSLog(@"GRUPPER IN findeGruppe:%@",actualImages);
				[self findeGruppe:[images objectForKey:[actualImages objectAtIndex:f]] mitrotationpin:rotationpin];
				
			}
		}
		}
	}
}


-(NSMutableArray *)getImagesForRotation:(mttPoint*)rotPin atImage:(mttImage *)rotImage {
	
	//NSArray *imagesForRotation = [[NSArray alloc] init];
	[neueGroupImages removeAllObjects];
	
	[self findeGruppe:rotImage mitrotationpin:rotPin];
	for(int x;x<[neueGroupImages count];x++ ){	NSLog(@"rotationimages!!!!!!: %@",[[neueGroupImages objectAtIndex:x] imagekey]); }
	return neueGroupImages;
	
	
	
}

-(void)removePin:(int) pintoremove {

	
	NSLog(@"in removePin pintoremove: %u", pintoremove);
	
	//NSNumber *pintoremovenumber = [[NSNumber alloc] initWithInt:pintoremove];
	//NSMutableArray *nextimages = [[NSMutableArray alloc] initWithArray:[pins objectForKey:pintoremovenumber]];
	
	//hier is mal testen angesagt
//NSNumber *pintoremovenumber = [[NSNumber alloc] initWithInt:pintoremove];
	//NSLog(@"imagestopin nachher %@", [pins objectForKey:pintoremovenumber]);
	
	//int test = (int)[nextimages objectAtIndex:0];
	//das passt mal!!!
	//NSLog(@"test %@, %i", nextimages, pinID);
	
	NSMutableArray *imagesForPin = [[NSMutableArray alloc] init];
	
	for (int i=0; i<images.count; i++) {
		mttImage* actualImage = [images objectForKey:[NSNumber numberWithInt:i]];
		
		[actualImage logPinPoints:actualImage.imagekey];
		
		if ([actualImage isPinInImage:pintoremove]) {
			NSLog(@"imagesForPin hinzugefügtes bild id: %@", actualImage.imagekey);
			[imagesForPin addObject:actualImage];
		}
	}
	
	//Check Kreis
	if ([self findeKreis:pintoremove]) {
		NSLog(@"Kreis gefunden");
		//Hier nur den pin löschen - nix weiter
		
		//NSMutableArray *imagesForPin = [[NSMutableArray alloc] init];
		/*
		for (int i=0; i<images.count; i++) {
			mttImage* actualImage = [images objectForKey:[NSNumber numberWithInt:i]];
			
			if ([actualImage isPinInImage:pintoremove]) {
				[imagesForPin addObject:actualImage];
			}
		}
		*/
		for (int i=0; i<[imagesForPin count]; i++) {
			mttImage* actualImage = [imagesForPin objectAtIndex:i];
			
			[actualImage deletePin:pintoremove];
		}
		
		[pins removeObjectForKey:[NSNumber numberWithInt:pintoremove]];
	
		
		
	} else {
		NSLog(@"kein Kreis gefunden");
		//Hier den Pin löschen, die Bilder des Pins aber merken
		//Die Gruppe löschen (als view entfernen) - auch aus der liste
		//Schauen welche Restgruppen anhand der Pins überbleiben und Restgruppen neu erstellen
		
		//mttPoint* removePin = [pins	objectForKey:[NSNumber numberWithInt:pintoremove]];
		
		NSMutableArray *imgOnRemovePinTemp = [[NSMutableArray alloc] initWithArray:[pins objectForKey:[NSNumber numberWithInt:pintoremove]]];
		NSMutableArray *imgOnRemovePin = [[NSMutableArray alloc] init];
		
		
		for (int i=0; i<[imgOnRemovePinTemp count]; i++) {
			[imgOnRemovePin addObject:[images objectForKey:[imgOnRemovePinTemp objectAtIndex:i]]];
		}
		
		
		//pin löschen
		[pins removeObjectForKey:[NSNumber numberWithInt:pintoremove]];
		//pins aus bildern löschnen

		
		for(int i=0;i<[imgOnRemovePin count];i++){
			
			//delete pins in images
			[[imgOnRemovePin objectAtIndex:i] deletePin:pintoremove];
			
			
			[neueGroupImages removeAllObjects];
			//hier kommt dann die rekursive funktion hin
			[self findeGruppe:[imgOnRemovePin objectAtIndex:i] mitrotationpin:NULL];
			NSLog(@"NEUER GRUPPER:,%@",neueGroupImages);
			
			
			//pinnedImages aktualisieren
			NSMutableArray *newGroupKeys = [[NSMutableArray alloc] init];
			for (int i=0; i<[neueGroupImages count]; i++) {
				[newGroupKeys addObject:[[neueGroupImages objectAtIndex:i] imagekey]];
			}
			
			for (int i=0; i<[neueGroupImages count]; i++) {
				[pinnedImages setObject:newGroupKeys forKey:[[neueGroupImages objectAtIndex:i] imagekey]];
				
			}
			
			for (id key in pinnedImages) {
				NSLog(@"---------------------    Pinned Images ---------------------------");
				NSLog(@"key: %@, value: %@", key, [pinnedImages objectForKey:key]);
				
			}

				 
		}
		
		
		
		
		//ursprüngliche gruppe löschen
		mttImage *searchImg = [imgOnRemovePin objectAtIndex:0];
		BOOL bla = NO;
		for (id key in imageGroups) {
			if ([[imageGroups objectForKey:key] isImageInGroup:searchImg] && bla == NO) {
				mttImageGroup *groupToDelete = [imageGroups objectForKey:key];
				[groupToDelete removeFromSuperview];
				[imageGroups removeObjectForKey:key];
				bla = YES;
			}
		}
		
		//Gruppen neu erstellen
		
		
		
		
		for (int i=0; i<[imagesForPin count]; i++) {
			NSLog(@"imagesforpin key: %@", [[imagesForPin objectAtIndex:i] imagekey]);
			//ist nur ein bild übergeblieben wird das bild eingefüg
			
			NSNumber *actualImageKey = [[imagesForPin objectAtIndex:i] imagekey];
			if ([[pinnedImages objectForKey:actualImageKey] count] == 1) {
				
				
				[self.view addSubview:[images objectForKey:actualImageKey]];
				[[images objectForKey:actualImageKey] setGestureRecognizersEnabled:YES];
				//???: Hier kackts ab. Bild lässt sich nimmer bewegen.
				NSLog(@"in einzelnes bild");
			
			//bleiben mehrere über, wird eine Gruppe erzeugt.	 
			} else {
				NSMutableArray* keysForGroup = [pinnedImages objectForKey:actualImageKey];
				
				// Init mit mainController frame
				//mttImageGroup* imageGroup = [[mttImageGroup alloc] initWithFrame:self.view.bounds];		
				
				// Init mit berechnetem Frame. ResizetoSubviews unten weiter ist überflüssig
				mttImageGroup* imageGroup = [[mttImageGroup alloc] initWithFrame:[self getGroupRectForImages:keysForGroup]];	
				
				imageGroup.delegate = self;
				imageGroup.imageGroupKey = imageGroupKey;
				//imageGroup.backgroundColor = [UIColor colorWithRed:2 green:2 blue:2 alpha:2];
				
				for(int i = keysForGroup.count-1; i>=0; i--){
					
					mttImage* actualImage = [images objectForKey:[keysForGroup objectAtIndex:i]];
					//NSLog(@"New Pin -----------------------");
					
					[imageGroup addSubview:actualImage];
					//NSLog(@"ImageFrame after x:%f, y:%f, w:%f, h:%f", actualImage.frame.origin.x, actualImage.frame.origin.y, actualImage.frame.size.width, actualImage.frame.size.height);
					//NSLog(@"imagePosition after x:%f, y:%f", actualImage.layer.position.x, actualImage.layer.position.y);
					//NSLog(@"GroupPosition x:%f, y:%f", imageGroup.layer.position.x, imageGroup.layer.position.y);
					
					//Gesture Recognizer für das Bild abschalten
					[actualImage setGestureRecognizersEnabled:NO];
					
					//Wenn die Pins angezeigt sind, sollen Sie ausgeschaltet werden
					[actualImage hideSubviews:YES];
					
					
				}
				
				[imageGroups setObject:imageGroup forKey:imageGroup.imageGroupKey];
				
				int newKey = [imageGroupKey intValue] + 1;
				imageGroupKey = [NSNumber numberWithInt:newKey];
				
				//[imageGroup resizeToSubviews];
				
				//NSLog(@"NEWS SIZE width: %f height: %f", size.width, size.height);
				
				[self.view addSubview:imageGroup];
				[self bringOptionViewToFront];
			}
		
		}
		
	}

	
	/*
	NSMutableArray *behandeltePins = [[NSMutableArray alloc] init];
	[behandeltePins addObject:pintoremovenumber];
	for(int i=1;i<[[pins objectForKey:pintoremovenumber] count];i++){
		NSLog(@"inremovePin in erster schleife"); 
		[self findeKreismitAnfangsImage:[[pins objectForKey:pintoremovenumber] objectAtIndex:0] schonbehandeltePins:behandeltePins naechstesImage:[[pins objectForKey:pintoremovenumber] objectAtIndex:i]];
	}
	 
	 */
	// [pintoremovenumber release];
	//for(int i=1;i<pinID;i++)
	//{
	//Hier werden die indexe vom pinid dictionary durchgelaufen bis zur maximum pinID (pinID-1)
	//}
}




-(void)setMttBackground:(mttImage *) selectedImage {
	
	if (bgImage != nil) {
		[bgImage removeFromSuperview];
	}
	
	bgImage = nil;
	
	
	//Background image erzeugen
	bgImage = [[mttBackgroundImage alloc] initWithImage:selectedImage.image];
	bgImage.delegate = self;
	
	//Aus dem Dictionary entfernen
	[images removeObjectForKey:selectedImage.imagekey];
	
	//mttBackgroundImage als subview hinzufügen
	[self.view insertSubview:bgImage atIndex:1];   //Index 1 weil hilfe den index 0 hat
	
	
	
	//isBgSet = YES;
	
	

}	
	

-(void)setImagesAlpha:(CGFloat) alpha {
	for (id key in images) {
		//Hier Animationsanfang!?
		CGContextRef context = UIGraphicsGetCurrentContext();
		[UIView beginAnimations:nil context:context];
		
		[UIView setAnimationDuration:1.0];
		
		[[images objectForKey:key] setAlpha:alpha];
		
		[UIView commitAnimations];
		
	}
}

-(void)setImagesInteraction:(BOOL) interaction {
	for (id key in images) {
		
		[[images objectForKey:key] setGestureRecognizersEnabled:interaction];
		
	}
}

-(void)bringViewToFront:(UIView *) subView {
	[self.view bringSubviewToFront:subView];
}

-(void)bringOptionViewToFront {
	[self.view bringSubviewToFront:optionView.view];
}

-(void)sendViewToBack:(UIView *) subView {
	[self.view sendSubviewToBack:subView];
}

-(void)removeImage:(NSNumber *) imageKey {
	[images removeObjectForKey:imageKey];
}

-(UIView *)getView {
	return self.view;
}

-(UIView *)getHelp {
	return self.help;
}

#pragma mark -
#pragma mark optionView Delegate Methods

-(void)presentHelpView:(UINavigationController *) navController {
	[self presentModalViewController:navController animated:YES];
}

#pragma mark -
#pragma mark HelpViewController Delegate Methods

-(void)didDismissHelpView {
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark init & dealloc

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

- (void)dealloc {
	
	optionView = NULL;
	[super dealloc];
	
}


@end
